import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
  ProForm,
  ProFormText,
  ProFormTextArea,
  ProFormSwitch,
  ProFormCheckbox,
} from '@ant-design/pro-components';
import { Button, Divider, Drawer, Modal, Space, message, Switch, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { Access, useAccess } from '@umijs/max';
import systemServices from '@/services/system';

const { queryRoleList, createRole, updateRole, deleteRole } = systemServices.RoleController;

// 处理删除角色
const handleRemove = async (selectedRows: API.RoleItem[]) => {
  const hide = message.loading('正在删除');
  try {
    // 调用删除API
    for (const row of selectedRows) {
      await deleteRole(row.id);
    }
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const RoleList: React.FC = () => {
  const [selectedRowsState, setSelectedRows] = useState<API.RoleItem[]>([]);
  const [currentRow, setCurrentRow] = useState<API.RoleItem>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const access = useAccess();
  
  // 处理角色状态切换
  const handleStatusChange = async (checked: boolean, record: API.RoleItem) => {
    message.success(`角色 ${record.name} 已${checked ? '启用' : '禁用'}`);
    // 在实际应用中，这里应该调用API更新角色状态
  };
  
  // 表格列定义
  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [{ required: true, message: '角色名称为必填项' }],
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'text',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
      render: (_, record) => (
        <Switch
          checked={record.status}
          onChange={(checked) => handleStatusChange(checked, record)}
        />
      ),
    },
    {
      title: '权限',
      dataIndex: 'permissions',
      search: false,
      render: (_, record) => (
        <>
          {record.permissions.map(permission => (
            <Tag color="blue" key={permission}>
              {permission}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space split={<Divider type="vertical" />}>
          <a
            key="edit"
            onClick={() => {
              setCurrentRow(record);
              setCreateModalVisible(true);
            }}
          >
            编辑
          </a>
          <a
            key="permissions"
            onClick={() => {
              setCurrentRow(record);
              setDrawerVisible(true);
            }}
          >
            权限设置
          </a>
          <a
            key="delete"
            onClick={() => {
              Modal.confirm({
                title: '确认删除',
                content: `确定要删除角色 ${record.name} 吗？`,
                onOk: async () => {
                  const hide = message.loading('正在删除');
                  try {
                    const response = await deleteRole(record.id);
                    if (response.code === '200') {
                      hide();
                      message.success('删除成功');
                      actionRef.current?.reload();
                    } else {
                      hide();
                      message.error(response.message || '删除失败');
                    }
                  } catch (error) {
                    hide();
                    message.error('删除失败，请重试');
                  }
                },
              });
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];

  return (
    <Access accessible={access.canAdmin}>
      <PageContainer
        header={{
          title: '角色管理',
          subTitle: '管理系统角色及其权限',
        }}
      >
        <ProTable<API.RoleItem>
          headerTitle="角色列表"
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrentRow(undefined);
                setCreateModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建角色
            </Button>,
          ]}
          request={async (params) => {
            try {
              const response = await queryRoleList();
              if (response.code === '200') {
                return {
                  data: response.data,
                  success: true,
                  total: response.data.length,
                };
              } else {
                message.error(response.message || '获取角色列表失败');
                return {
                  data: [],
                  success: false,
                  total: 0,
                };
              }
            } catch (error) {
              message.error('获取角色列表失败');
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => setSelectedRows(selectedRows),
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
              </div>
            }
          >
            <Button
              onClick={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              批量删除
            </Button>
          </FooterToolbar>
        )}
        
        <Drawer
          width={600}
          open={drawerVisible}
          onClose={() => {
            setDrawerVisible(false);
            setCurrentRow(undefined);
          }}
          closable={false}
          title="角色权限设置"
        >
          {currentRow?.name && (
            <>
              <ProDescriptions<API.RoleItem>
                column={2}
                title={currentRow?.name}
                request={async () => ({
                  data: currentRow || {},
                })}
                params={{
                  id: currentRow?.name,
                }}
                columns={columns.filter(col => col.dataIndex !== 'option')}
              />
              <div style={{ marginTop: 20 }}>
                <h3>权限分配</h3>
                <div>
                  {currentRow.permissions.map(permission => (
                    <Tag color="blue" key={permission} style={{ margin: '0 8px 8px 0' }}>
                      {permission}
                    </Tag>
                  ))}
                </div>
                <p>在实际应用中，这里应该展示权限树或权限列表，供用户选择分配给角色</p>
              </div>
            </>
          )}
        </Drawer>
        
        <Modal
          title={`${currentRow ? '编辑' : '新建'}角色`}
          width={800}
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            setCurrentRow(undefined);
          }}
          footer={null}
        >
          <ProForm
            initialValues={currentRow || { status: true }}
            onFinish={async (values) => {
              const hide = message.loading(`正在${currentRow ? '更新' : '创建'}角色`);
              try {
                if (currentRow?.id) {
                  // 更新角色
                  const response = await updateRole(currentRow.id, values as API.RoleItem);
                  if (response.code === '200') {
                    hide();
                    message.success('更新角色成功');
                    setCreateModalVisible(false);
                    setCurrentRow(undefined);
                    actionRef.current?.reload();
                    return true;
                  } else {
                    hide();
                    message.error(response.message || '更新角色失败');
                    return false;
                  }
                } else {
                  // 创建角色
                  // 不需要传递ID，MySQL会自动生成
                  const { name, description, status, permissions } = values as API.RoleItem;
                  const roleData = {
                    name,
                    description,
                    status,
                    permissions,
                    // createdAt在API服务中会自动添加
                  };
                  
                  const response = await createRole(roleData);
                  if (response.code === '200') {
                    hide();
                    message.success('创建角色成功');
                    setCreateModalVisible(false);
                    setCurrentRow(undefined);
                    actionRef.current?.reload();
                    return true;
                  } else {
                    hide();
                    message.error(response.message || '创建角色失败');
                    return false;
                  }
                }
              } catch (error) {
                hide();
                message.error(`${currentRow ? '更新' : '创建'}角色失败，请重试`);
                console.error('角色操作失败:', error);
                return false;
              }
            }}
            submitter={{
              searchConfig: {
                submitText: '保存',
                resetText: '取消',
              },
              render: (props, dom) => {
                return (
                  <div style={{ textAlign: 'right' }}>
                    <Button 
                      style={{ marginRight: 8 }} 
                      onClick={() => {
                        setCreateModalVisible(false);
                        setCurrentRow(undefined);
                      }}
                    >
                      取消
                    </Button>
                    <Button type="primary" onClick={() => props.form?.submit()}>
                      保存
                    </Button>
                  </div>
                );
              },
            }}
          >
            <ProFormText
              name="name"
              label="角色名称"
              placeholder="请输入角色名称"
              rules={[
                {
                  required: true,
                  message: '角色名称不能为空',
                },
              ]}
            />
            <ProFormTextArea
              name="description"
              label="角色描述"
              placeholder="请输入角色描述"
              rules={[
                {
                  required: true,
                  message: '角色描述不能为空',
                },
              ]}
            />
            <ProFormSwitch
              name="status"
              label="状态"
              checkedChildren="启用"
              unCheckedChildren="禁用"
            />
            <div style={{ marginBottom: 16 }}>
              <div style={{ marginBottom: 8 }}>权限设置</div>
              <ProFormCheckbox.Group
                name="permissions"
                layout="vertical"
                options={[
                  {
                    label: '用户管理',
                    value: 'user:manage',
                  },
                  {
                    label: '用户查看',
                    value: 'user:view',
                  },
                  {
                    label: '用户编辑',
                    value: 'user:edit',
                  },
                  {
                    label: '用户删除',
                    value: 'user:delete',
                  },
                  {
                    label: '角色管理',
                    value: 'role:manage',
                  },
                  {
                    label: '角色查看',
                    value: 'role:view',
                  },
                  {
                    label: '角色编辑',
                    value: 'role:edit',
                  },
                  {
                    label: '角色删除',
                    value: 'role:delete',
                  },
                  {
                    label: '系统设置',
                    value: 'system:settings',
                  },
                  {
                    label: '数据导出',
                    value: 'data:export',
                  },
                  {
                    label: '数据导入',
                    value: 'data:import',
                  },
                ]}
              />
            </div>
          </ProForm>
        </Modal>
      </PageContainer>
    </Access>
  );
};

export default RoleList;
